<!--  -->
<template>
  <div class="">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容"   v-model="queryInfo.findKeyWord" clearable>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="findUser()"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addUser()">添加用户</el-button></el-col
        >
      </el-row>
      <!-- 卡片 -->
      <el-table :data="adminData" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change = "switchChangeState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeUserInfo(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                 @click="assignroles(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="count">
    </el-pagination>
    </el-card>
  
  <!-- 对话框 -->
<el-dialog
  title="添加用户"
  :visible.sync="showFlag"
  width="50%"
  @close="closeForm()"
>
 
<el-form  :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="100px">
  <!-- :model和v-model区别???? -->
  <el-form-item label="用户名" prop="username" >
    <el-input v-model="addForm.username" :disabled="dischangeUsername"></el-input>
  </el-form-item>
    <el-form-item label="密码" prop="password" v-show="!dischangeUsername">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机号" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancleChange()">取 消</el-button>
    <el-button type="primary" @click="addUserBtn()"  v-show="!dischangeUsername">确 定</el-button>
    <el-button type="primary" @click="changeuserBtn()"   v-show="dischangeUsername">修 改</el-button>
  </span>
</el-dialog>



<el-dialog
  title="分配角色"
  :visible.sync="dialogVisible"
  width="50%"
 >
  <h4 v-if="adminData[currentIndex]">当前的用户:{{adminData[currentIndex].username}}</h4>
  <h4 v-if="adminData[currentIndex]">当前的角色:{{adminData[currentIndex].role_name}}</h4>
  <div>  <h4>分配新角色:</h4>
    <el-select v-model="selectRoleId" placeholder="请选择">
    <el-option
      v-for="(item) in roles_array"
      :key="item.role"
      :label="item.role"
      :value="item.role"
      :disabled="item.disabled">
    </el-option>
  </el-select></div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancleUpdateRoles()">取 消</el-button>
    <el-button type="primary" @click="updateRoles()">确 定</el-button>
  </span>
</el-dialog>





  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var checkMail = (rule,value,cb)=>{
      var mailCode = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if(mailCode.test(value)){return cb()}
      else cb(new Error("请输入正确的邮箱"))
    }
    var checkPhone = (rule,value,cb)=>{
       var phoneCode = /^1[3456789]\d{9}$/
       if(phoneCode.test(value)){return cb()}
       else cb(new Error("请输入正确的手机号"))
    }

    //这里存放数据
    return {
      adminData: [],
       queryInfo:{
        findKeyWord:'',
        pageNum:1,
        pageSize:4
      },
      count:0,
      mg_state:false,
      showFlag:false,
      addFormRules:{
        username:[
          {required:true,message:"请输入用户名",trigger:"blur"},
          {min:1,max:4 ,message:"长度为1-4" }
        ],
        password:'',
        email:[
               {required:true,message:"请输入密码",trigger:"blur"},
               {validator:checkMail}
        ],
        mobile:[
               {required:true,message:"请输入密码",trigger:"blur"},
               {validator:checkPhone}
        ]
      },
      addForm:{
        username:'',
        password:'',
        email:"",
        mobile:''
      },
      dischangeUsername:false,
      id:5,
      dialogVisible:false,
      role_array:[],
      selectRoleId:'',
      currentIndex:0,
      roles_array:[{role:"超级管理员",disabled:true},{role:"银河天使",disabled:true},{role:"测试用户1",disabled:false},
      {role:"测试用户2",disabled:false},{role:"测试用户3",disabled:false},{role:"测试用户4",disabled:false}]
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async requsetData() {
      const { data } = await this.$http.get("/user/admin",{params:this.queryInfo});
      if (data.err == 0) {
      data.data.forEach((item,index)=>{          
           if(item.mg_state==1){
             item.mg_state =true
           }else{
             item.mg_state = false
           }
        }) 
        this.adminData = data.data;
        this.count = data.count
        this.role_array = data.role_arry
        console.log(data);
        this.$message.success(data.msg);
      }
    },
    handleSizeChange(val){
        this.queryInfo.pageSize = val
        this.requsetData()
    },
    handleCurrentChange(val){
        this.queryInfo.pageNum = val
        this.requsetData()
    },
  async  switchChangeState(e){
    let parmas = {id:e.id,mg_state:e.mg_state==true?1:0}
    let {data} = await this.$http.get("/user/update/mg_state",{params:parmas})
    console.log(data);//为什么打印的是underfine(因为你解构的是data数据)
    if(data.err==0){
      this.$message.success("修改状态成功")
    }else{
      this.$message.error("修改状态失败")
    }
    },
    findUser(){
      this.requsetData()
    },
    addUser(){
      this.showFlag =true
      this.dischangeUsername = false
      this.addForm.username = ''
      this.addForm.email = ''
      this.addForm.mobile = ''
      this.addFormRules.password =[
            {required:true,message:"请输入密码",trigger:"blur"},
                   {min:6,max:12 ,message:"长度为6-12" }
        ]
    },
    closeForm(){
      this.$refs.ruleForm.resetFields()
    },
    addUserBtn(){
  
      this.$refs.ruleForm.validate(async valid=>{
        if(valid){
        const {data}  = await this.$http.get("/user/add/admin",{params:this.addForm})
        console.log(data);
     if(data.err==0){
       this.$message.success("添加用户成功")
        this.requsetData()
        this.showFlag = false
     }else if(data.err==-1){
       this.$message.error("用户名重复了哦")
     }
        }
        
      })
    },
    changeUserInfo(e){
      this.showFlag = true
      this.dischangeUsername = true
      this.id = e.id
      console.log(e);
      this.addForm.username = e.username
      this.addForm.email = e.email
      this.addForm.mobile = e.mobile
    },
    changeuserBtn(){
       this.addFormRules.password = ''
       let parmas = {id:this.id,mobile:this.addForm.mobile,email:this.addForm.email}
      this.$refs.ruleForm.validate(async valid=>{
         if(valid){
        const {data} =await this.$http.get("/user/update/admin",{params:parmas})
        console.log(data);
        if(data.err==0){
          this.$message.success("修改成功")
          this.showFlag = false
        }
         }else{
           this.$message.error("修改失败")
           return ;
         }
      })
    },
    cancleChange(){
      this.showFlag = false
      // this.addForm.username = ''
      // this.addForm.email = ''
      // this.addForm.mobile = ''
    },
    removeUserById(e){
      console.log(e.id);
      let parmas = {id:e.id}
  this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          this.$http.get("/user/delete/admin",{params:parmas}).then((res)=>{
           console.log(res);
           if(res.data.err==0){
             this.$message.success("删除用户成功")
             this.requsetData()
           }else{
               this.$message.error("删除用户失败")
           }
         })
        }).catch((err) => {        
        });
    },
    assignroles(id){
      this.dialogVisible = true
      console.log(id);
      this.currentIndex = id-1
    },
    cancleUpdateRoles(){
      this.dialogVisible = false
      this.$message.warning("您取消了权限操作!")
    },
    updateRoles(){
      this.dialogVisible = false
      console.log(this.selectRoleId);
      let data = {id:this.currentIndex+1,role_name:this.selectRoleId}
      this.$confirm('此操作将修改该文件的权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'}).then((res)=>{
            this.$http.post('/user/update/admin/role_name',data).then(res=>{
              console.log(res);
              if(res.data.err==0){
                this.$message.success("权限修改成功!")
                this.requsetData()
              }else{
                this.$message.success("权限修改失败!")
              }
            })
          }).catch(err=>{})
      
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.requsetData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  deactivated() {},
};
</script>
<style  scoped>
.el-table{
    margin-top: 15px;
    margin-bottom: 15px;
}
</style>